package com.Controller;

import com.Service.CategoryService;
import com.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin/category")
public class AdminCategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public String list(Model model){
        List<Category> categoryList = categoryService.findAll();
        model.addAttribute("categoryList",categoryList);
        return "admin/category/list";
    }

    @GetMapping("/addPage")
    public String addPage(Model model){
        model.addAttribute("parentList", categoryService.findAll());
        return "admin/category/add";
    }

    @PostMapping("/add")
    public String add(Category category){
        category.setParentId(0L);
        categoryService.add(category);
        return "redirect:/admin/category/list";
    }

    @GetMapping("/editPage")
    public String editPage(@RequestParam("id") Long id, Model model){
        Category category=categoryService.findById(id);
        model.addAttribute("category",category);
        model.addAttribute("parentList",categoryService.findAll());
        return "admin/category/add";
    }

    @PostMapping("/edit")
    public String edit(Category category){
        category.setParentId(0L);
        categoryService.update(category);
        return "redirect:/admin/category/list";
    }

    @GetMapping("/delete")
    public String delete(@RequestParam("id") Long id, RedirectAttributes redirectAttributes) {
        try {
            categoryService.delete(id);
            redirectAttributes.addFlashAttribute("successMessage", "删除成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除失败：该拼团活动有关联数据，无法删除！");
        }
        return "redirect:/admin/category/list";
    }
}
